package com.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@Component
@RefreshScope
public class IpRequestGlobalFilter implements GlobalFilter, Ordered {


    /**
     * 最大请求次数
     */
    @Value("${config.maxRequestCount}")
    private int maxRequestCount;

    /**
     * 多长时间段
     */
    @Value("${config.requestTime}")
    private long requestTime;

    private static ConcurrentHashMap<String, List<Long>> ipRegistryMap = new ConcurrentHashMap<>();

    private static List<Long> ipRegistryList = new ArrayList<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        String path = request.getURI().getPath();
        // 判断地址是那个接口，注册接口
        if(path.contains("register")){
            //当前时间往前推1分钟
            // 获取当前时间
            Long currentTime = System.currentTimeMillis();
            //  拿到当前ip的请求的时间，和当前时间对比，如果时在时间范围之内,次数也在范围之内，就放行
            List<Long> list = ipRegistryMap.get(clientIp);
            Integer count = 0;
            if (list != null ){


            for (Long aLong : list) {
                long  time = aLong - currentTime;
                // 如果在请求范围之内 则请求加一
                if (time > requestTime ){
                    count++;
                }else {
                    // 在时间之外的就移除它，防止list 一直过大
                    list.remove(aLong);
                }
            }
            }
            // 如果某个时间段 请求次数有超过设定的阈值
            if (count > maxRequestCount ){
                response.setStatusCode(HttpStatus.SEE_OTHER);
                String data = "请稍后再试";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }

            ipRegistryList.add(System.currentTimeMillis());
            ipRegistryMap.put(clientIp,ipRegistryList);
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
